#include "PixelImage.h"

using namespace std;

PixelImage::PixelImage(char * fileName)
{
  ifstream sampleImage(fileName);
  string lineInput;

  /* Initializations */
  pixelAddressCounter = 0;
  currentXPosition = 0;
  currentYPosition = 0;

  if(!sampleImage)
  {
    cout << "File Could Not Be Opened" << endl;
  }
  else
  {
    //Get PNM File Type
    sampleImage >> lineInput;

    // Detect Correct PNM File
    if(lineInput.at(1) == '1')
    {
      cout << "Binary PNM File Found" << endl << endl;
      // Get Junk Data from the line
      getline(sampleImage, lineInput);

      // Get Author Information (Easiest Way)
      getline(sampleImage, lineInput);
      cout << lineInput << endl << endl;

      // Get Size Information
      sampleImage >> height;
      sampleImage >> width;
      processors = new MultProcessor(width, height);
      
      LoadImageIntoMatrix(&sampleImage);
      
    }
    else
    {
      cout << "This File Format is not Supported" << endl;
    }
  }
}

MultProcessor * PixelImage::GetLoadedImage(void)
{
  return processors;
}

void PixelImage::LoadImageIntoMatrix(ifstream * pixelFile)
{
  unsigned int loopCount;
  string lineInput;

  while(*pixelFile)
  {
    *pixelFile >> lineInput;
    for(loopCount = 0 ; loopCount < lineInput.length() ; loopCount++ )
    {
      if('1' == lineInput.at(loopCount))
      {
        std::cout << "Adding ";
        processors->SetProcessorPixel(currentXPosition, currentYPosition, 1);
      }

      /* Insert Pixel */

      if(!IncrementToNextPixelPosition())
      {
        while(*pixelFile) *pixelFile >> lineInput;
        std::cout << std::endl << std::endl;
        break;
      }
    }
  }
}


bool PixelImage::IncrementToNextPixelPosition(void)
{
  if(currentYPosition == (height - 1))
  {
    if(currentXPosition == (width - 1))
    {
      return 0;
    }
    currentYPosition = 0;
    currentXPosition++;
  }
  else
  {
    currentYPosition++;
  }
  return 1;
}



PixelImage::~PixelImage(void)
{
}

